'use strict';

const db = uniCloud.database();
const uniIdCommon = require('uni-id-common');

exports.main = async (event, context) => {
  // 1. 验证用户身份
  const token = context.uniIdToken || event.uniIdToken;
  if (!token) {
    return { code: 401, msg: '请先登录' };
  }
  
  const uniId = uniIdCommon.createInstance({ context });
  const tokenRes = await uniId.checkToken(token);
  if (tokenRes.code !== 0) {
    return { code: 401, msg: '登录状态已失效' };
  }
  
  const userId = tokenRes.uid;
  
  try {
    // 2. 获取任务统计数据
    const taskListRes = await db.collection('taskList')
      .where({ publisher_id: userId })
      .get();
    
    const receivedTaskRes = await db.collection('taskList')
      .where({ receiver_id: userId })
      .get();
    
    // 计算任务统计
    const publishedCount = taskListRes.data.length;
    const completedCount = taskListRes.data.filter(task => task.status === 'completed').length;
    // 修复：用户作为接单者的进行中任务数量
    const processingCount = receivedTaskRes.data.filter(task => 
      task.status === 'processing' || task.status === 'pending_review'
    ).length;
    
    // 修复收入统计逻辑 - 只查询接单者收入
    const incomeRes = await db.collection('task_income_records')
      .where({ 
        receiver_id: userId,
        status: 'completed'
      })
      .get();
    
    // 计算累计收入（接单者获得的收入）
    const totalIncome = incomeRes.data
      .reduce((sum, record) => sum + (record.reward_amount || 0), 0);
    
    // 计算本月收入
    const currentMonth = new Date().getMonth();
    const currentYear = new Date().getFullYear();
    const monthlyIncome = incomeRes.data
      .filter(record => {
        const recordDate = new Date(record.complete_time || record.create_time);
        return recordDate.getMonth() === currentMonth &&
               recordDate.getFullYear() === currentYear;
      })
      .reduce((sum, record) => sum + (record.reward_amount || 0), 0);
    
    // 3. 获取圈子统计数据
    const circleRes = await db.collection('add-content')
      .where({ user_id: userId, content_type: 'post' })
      .get();
    
    const commentRes = await db.collection('user-comment')
      .where({ author_id: userId })
      .get();
    
    // 计算圈子统计
    const postCount = circleRes.data.length;
    const commentCount = commentRes.data.length;
    const likeCount = circleRes.data.reduce((sum, post) => sum + (post.like_count || 0), 0);
    
    // 获取用户点赞数据
    const userLikesRes = await db.collection('user-likes')
      .where({ user_id: userId })
      .count();
    
    const userLikesCount = userLikesRes.total || 0;
    console.log('【getUserStats】用户点赞数据:', { userId, userLikesCount, userLikesRes });
    
    // 4. 获取活动统计数据
    const activityRes = await db.collection('add-content')
      .where({ user_id: userId, content_type: 'activity' })
      .get();
    
    const activityParticipantRes = await db.collection('activity_participants')
      .where({ user_id: userId })
      .get();
    
    // 计算活动统计
    const publishedActivityCount = activityRes.data.length;
    const participatedActivityCount = activityParticipantRes.data.length;
    
    // 5. 获取积分统计
    const scoreRes = await db.collection('user-score')
      .where({ user_id: userId })
      .get();
    
    const totalScore = scoreRes.data.reduce((sum, record) => sum + (record.score || 0), 0);
    
    return {
      code: 200,
      msg: '获取成功',
      data: {
        taskData: [
          { label: '发布任务', value: publishedCount, type: 'published' },
          { label: '进行中任务', value: processingCount, type: 'processing' },
          { label: '完成任务', value: completedCount, type: 'completed' }
        ],
        circleData: [
          { label: '发帖数', value: postCount },
          { label: '评论数', value: commentCount },
          { label: '获赞数', value: likeCount },
          { label: '我的点赞', value: userLikesCount }
        ],
        activityData: [
          { label: '发布活动', value: publishedActivityCount },
          { label: '参与活动', value: participatedActivityCount }
        ],
        totalScore: totalScore,
        // 新增数据字段，供钱包页面和信用页面使用
        totalIncome: totalIncome,
        monthlyIncome: monthlyIncome,
        averageRating: 4.8, // 平均评分，需要从评价表计算
        totalRatings: 0 // 评价总数，需要从评价表计算
      }
    };
  } catch (error) {
    console.error('获取用户统计失败:', error);
    return {
      code: 500,
      msg: '获取统计数据失败',
      error: error.message
    };
  }
};
